package com.nit.lab.service.system.impl;

import com.alibaba.fastjson.JSONObject;
import com.nit.lab.dto.basic.StudentDTO;
import com.nit.lab.dto.basic.TeacherDTO;
import com.nit.lab.dto.basic.UserDTO;
import com.nit.lab.dto.system.AccountDTO;
import com.nit.lab.dto.system.PermissionDTO;
import com.nit.lab.dto.system.RoleDTO;
import com.nit.lab.dto.system.TokenDTO;
import com.nit.lab.dto.utils.OpResultDTO;
import com.nit.lab.service.basic.StudentService;
import com.nit.lab.service.basic.TeacherService;
import com.nit.lab.service.basic.UserService;
import com.nit.lab.service.system.AccountService;
import com.nit.lab.service.system.RoleService;
import com.nit.lab.utils.JWTUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AccountServiceImpl implements AccountService {

    @Autowired(required = false)
    private UserService userService;
    @Autowired(required = false)
    private RoleService roleService;
    @Autowired(required = false)
    private TeacherService teacherService;
    @Autowired(required = false)
    private StudentService studentService;
    @Autowired(required = false)

    @Value(value = "${application.jwt.expire}")
    private Integer expire;

    @Override
    public JSONObject loginCheck(String loginName, String loginPwd, Integer loginType) throws Exception {
        JSONObject jsonObject = new JSONObject();
        TokenDTO tokenDTO = new TokenDTO();
        OpResultDTO opResult = new OpResultDTO();
        AccountDTO accountDTO = new AccountDTO();
        if (loginType == 1) { // 管理员
            UserDTO userDto = userService.loginCheck(loginName);
            if (userDto == null || !userDto.getLoginPwd().equals(loginPwd)) {
                opResult.setResult(JSONObject.parseObject("{ isLogin: true }"));
                jsonObject.put("data", opResult);
                jsonObject.put("message", "账户或密码错误");
                jsonObject.put("status", 401);
            } else {
                accountDTO.setId(userDto.getUserId());
                accountDTO.setName(userDto.getUserName());
                accountDTO.setRoleId(String.valueOf(userDto.getRoleId()));
                // 生成签名DTO，包含账号ID，账户类型
                tokenDTO.setAccountId(userDto.getUserId());
                tokenDTO.setRoleId(userDto.getRoleId());
                accountDTO.setToken(JWTUtil.createSign(tokenDTO.toString(), expire));
                opResult.setResult(accountDTO);
                jsonObject.put("data", opResult);
                jsonObject.put("message", "");
                jsonObject.put("status", 200);
            }
        } else if (loginType == 2) { // 教师
            TeacherDTO teacherDTO = teacherService.loginCheck(loginName);
            if (teacherDTO == null || !teacherDTO.getTeacherPwd().equals(loginPwd)) {
                opResult.setResult(JSONObject.parseObject("{ isLogin: true }"));
                jsonObject.put("data", opResult);
                jsonObject.put("message", "账户或密码错误");
                jsonObject.put("status", 401);
            } else {
                accountDTO.setId(teacherDTO.getTeacherId());
                accountDTO.setName(teacherDTO.getTeacherName());
                accountDTO.setRoleId(String.valueOf(teacherDTO.getRoleId()));
                // 生成签名DTO，包含账号ID，学校ID，账户类型
                tokenDTO.setAccountId(teacherDTO.getTeacherId());
                tokenDTO.setRoleId(teacherDTO.getRoleId());
                tokenDTO.setSchoolId(teacherDTO.getSchoolId());
                accountDTO.setToken(JWTUtil.createSign(tokenDTO.toString(), expire));
                opResult.setResult(accountDTO);
                jsonObject.put("data", opResult);
                jsonObject.put("message", "");
                jsonObject.put("status", 200);
            }
        } else if (loginType == 3) { // 学生
            StudentDTO studentDTO = studentService.loginCheck(loginName);
            if (studentDTO == null || !studentDTO.getStudentPwd().equals(loginPwd)) {
                opResult.setResult(JSONObject.parseObject("{ isLogin: true }"));
                jsonObject.put("data", opResult);
                jsonObject.put("message", "账户或密码错误");
                jsonObject.put("status", 401);
            } else {
                accountDTO.setId(studentDTO.getStudentId());
                accountDTO.setName(studentDTO.getStudentName());
                accountDTO.setRoleId(String.valueOf(studentDTO.getRoleId()));
                tokenDTO.setRoleId(studentDTO.getRoleId());
                // 生成签名DTO，包含账号ID，账户类型
                tokenDTO.setAccountId(studentDTO.getStudentId());
                accountDTO.setToken(JWTUtil.createSign(tokenDTO.toString(), expire));
                opResult.setResult(accountDTO);
                jsonObject.put("data", opResult);
                jsonObject.put("message", "");
                jsonObject.put("status", 200);
            }
        }

         else { // 其他情况
            opResult.setResult(JSONObject.parseObject("{ isLogin: true }"));
            jsonObject.put("data", opResult);
            jsonObject.put("message", "账户或密码错误");
            jsonObject.put("status", 401);
        }
        return jsonObject;
    }

    @Override
    public AccountDTO getInfo(String token) throws Exception {
        AccountDTO accountDTO = new AccountDTO();
        TokenDTO tokenDTO = JWTUtil.verifyToken(token);
        Integer roleId = tokenDTO.getRoleId();
        if (tokenDTO.getRoleId() == 1) { // 管理员
            UserDTO userDto = userService.getByUserId(tokenDTO.getAccountId());
            accountDTO.setId(userDto.getUserId());
            accountDTO.setName(userDto.getUserName());
            accountDTO.setUsername(userDto.getLoginName());
            accountDTO.setAvatar(userDto.getUserImage());
            accountDTO.setTelephone(userDto.getUserPhone());
            accountDTO.setCreateTime(userDto.getGmtCreate());
            accountDTO.setRoleId(String.valueOf(userDto.getRoleId()));
        } else if (tokenDTO.getRoleId() == 2) { // 教师
            TeacherDTO teacherDTO = teacherService.getByTeacherId(tokenDTO.getAccountId());
            accountDTO.setId(teacherDTO.getTeacherId());
            accountDTO.setName(teacherDTO.getTeacherName());
            accountDTO.setUsername(teacherDTO.getTeacherCode());
            accountDTO.setTelephone(teacherDTO.getTeacherPhone());
            accountDTO.setCreateTime(teacherDTO.getGmtCreate());
            accountDTO.setRoleId(String.valueOf(teacherDTO.getRoleId()));
        } else if (tokenDTO.getRoleId() == 3) { // 学生
            StudentDTO studentDTO = studentService.getByStudentId(tokenDTO.getAccountId());
            accountDTO.setId(studentDTO.getStudentId());
            accountDTO.setName(studentDTO.getStudentName());
            accountDTO.setUsername(studentDTO.getStudentCode());
            accountDTO.setCreateTime(studentDTO.getGmtCreate());
            accountDTO.setRoleId(String.valueOf(studentDTO.getRoleId()));
        }

        accountDTO.setToken(JWTUtil.createSign(tokenDTO.toString(), expire));
        List<PermissionDTO> listPermissionDto = roleService.listPermissionByRoleId(roleId);
        RoleDTO roleDTO = roleService.getRoleByRoleId(roleId);
        roleDTO.setPermissions(listPermissionDto);
        accountDTO.setRole(roleDTO);
        return accountDTO;
    }
}
